/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.test.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

public class MongoTraceLoggerRedirector {
    static {
        java.util.logging.Logger loggerForMongo = java.util.logging.Logger.getLogger("com.mongodb.TRACE");
        loggerForMongo.setUseParentHandlers(false);
        loggerForMongo.addHandler(new MongoTraceLoggerHandler());
        loggerForMongo.setLevel(java.util.logging.Level.ALL);
    }

    public static void init() {
    }

    static class MongoTraceLoggerHandler extends Handler {
        final static Logger logger = LoggerFactory.getLogger("mongo.TRACE");

        @Override
        public void publish(LogRecord record) {
            if (!getLevel().equals(Level.OFF)) {
                if (record.getLevel().intValue() <= Level.FINE.intValue()) {
                    logger.trace(record.getMessage());
                } else if (record.getLevel().intValue() <= Level.CONFIG.intValue()) {
                    logger.debug(record.getMessage());
                } else if (record.getLevel().intValue() <= Level.INFO.intValue()) {
                    logger.info(record.getMessage());
                } else if (record.getLevel().intValue() <= Level.WARNING.intValue()) {
                    logger.warn(record.getMessage());
                } else if (record.getLevel().intValue() <= Level.SEVERE.intValue()) {
                    logger.error(record.getMessage());
                } else {
                    logger.error(record.getMessage());
                }
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    }
}
